package com.tchy.cloud.controller;

import com.tchy.cloud.entity.CQuesQuesEntity;
import com.tchy.cloud.entity.CQuestionnaireEntity;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 量表问题
 * xmweilove
 */
@Controller
@RequestMapping("/quesquesController")
public class CQuesQuesController extends BaseController {
    private static final Logger logger = Logger.getLogger(CQuesQuesController.class);

    @Autowired
    private CommonService commonService;

    /**
     * 量表问题展示页面跳转
     *
     * @return
     */
    @RequestMapping(params = "index")
    public ModelAndView index(HttpServletRequest request) {
        String qsId = request.getParameter("id");//量表id
        request.setAttribute("qsId", qsId);
        return new ModelAndView("clound/quesques/index");
    }

    /**
     * 纬度创建时候——量表问题选择展示页面跳转
     *
     * @return
     */
    @RequestMapping(params = "selectList")
    public ModelAndView selectList(HttpServletRequest request) {
        String qsId = request.getParameter("id");//量表id
        String qqids = request.getParameter("qqids");//关联的问题id组合
        request.setAttribute("qsId", qsId);
        request.setAttribute("qqids", qqids);
        return new ModelAndView("clound/quesques/selectList");
    }

    /**
     * 问题选项——不回答问题选项关联
     *
     * @return
     */
    @RequestMapping(params = "selectList_noanswer")
    public ModelAndView selectList_noanswer(HttpServletRequest request) {
        String qqid = request.getParameter("qqid");//问题id
        String qsid = request.getParameter("qsid");//量表id
        String qqids = request.getParameter("qqids");//选项关联的问题id组合
        request.setAttribute("qsid", qsid);
        request.setAttribute("qqid", qqid);
        request.setAttribute("qqids", qqids);

        return new ModelAndView("clound/quesques/selectList_noanswer");
    }

    /**
     * 量表问题展示数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(CQuesQuesEntity quesEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        String qsId = request.getParameter("qsId");
        CriteriaQuery cq = new CriteriaQuery(CQuesQuesEntity.class, dataGrid);

        cq.eq("deleted", 0);
        cq.createAlias("questEntity", "as_questEntity");
        cq.eq("as_questEntity.id", Integer.valueOf(qsId));

        cq.addOrder("quesNo", SortDirection.asc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, quesEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 量表问题展示数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "select_datagrid")
    public void select_datagrid(CQuesQuesEntity quesEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        String qsId = request.getParameter("qsId");
        CriteriaQuery cq = new CriteriaQuery(CQuesQuesEntity.class, dataGrid);

        cq.createAlias("questEntity", "as_questEntity");
        cq.eq("as_questEntity.id", Integer.valueOf(qsId));
        cq.eq("deleted", 0);
        cq.eq("effective", 1);

        cq.addOrder("quesNo", SortDirection.asc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, quesEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 量表问题展示数据_选择问题选项后需要关联的不回答问题列表数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "datagrid_noanswer_select")
    public void datagrid_noanswer_select(CQuesQuesEntity quesEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        String qsId = request.getParameter("qsid");//量表id
        String qqid = request.getParameter("qqid");//问题id
        CriteriaQuery cq = new CriteriaQuery(CQuesQuesEntity.class, dataGrid);

        cq.createAlias("questEntity", "as_questEntity");
        cq.eq("as_questEntity.id", Integer.valueOf(qsId));//归属与某量表的问题
        cq.notEq("id", Integer.valueOf(qqid));//排除本身这个问题
        cq.eq("effective", 1);
        cq.eq("deleted", 0);

        cq.addOrder("quesNo", SortDirection.asc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, quesEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 新增或编辑页面跳转
     *
     * @param entity
     * @param req
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(CQuesQuesEntity entity, HttpServletRequest req) {
        String qsId = req.getParameter("qsId");//量表id
        if (entity.getId() != null) {
            entity = commonService.getEntity(CQuesQuesEntity.class, entity.getId());
        } else {
            CQuestionnaireEntity questEntity = commonService.getEntity(CQuestionnaireEntity.class, Integer.valueOf(qsId));
            entity.setQuestEntity(questEntity);
        }

        req.setAttribute("entity", entity);
        return new ModelAndView("clound/quesques/addorupdate");
    }

    /**
     * 明细查看
     *
     * @param entity
     * @param req
     * @return
     */
    @RequestMapping(params = "detail")
    public ModelAndView detail(CQuestionnaireEntity entity, HttpServletRequest req) {
        if (entity.getId() != null) {
            entity = commonService.getEntity(CQuestionnaireEntity.class, entity.getId());
        }
        req.setAttribute("entity", entity);
        return new ModelAndView("clound/quest/detail");
    }

    /**
     * 验证问题名称是否存在，存在不允许提交
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "checkName")
    @ResponseBody
    public Map<String, String> checkName(HttpServletRequest request) {
        String id = request.getParameter("id");//问题主键
        String name = request.getParameter("name");//问题名称
        String quesId = request.getParameter("quesId");//量表主键
        Map<String, String> map = new HashMap<>();
        try {
            if (id != "") {//修改操作
                CQuesQuesEntity entity = commonService.getEntity(CQuesQuesEntity.class, Integer.valueOf(id));
                if (!name.equals(entity.getName())) {
                    String sql = "select count(*) num from c_ques_ques where name= ? and questionnaire_id=? and ques_ques_id !=? and deleted=0";
                    List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name, quesId, Integer.valueOf(id)});
                    Map returnMmap = list.get(0);
                    if (Integer.valueOf(String.valueOf(returnMmap.get("num"))) == 0) {
                        map.put("code", "0");
                        map.put("msg", "success");
                    } else {
                        map.put("code", "1");
                        map.put("msg", "此问题名称已经存在，请更改后重试。");
                    }
                }

            } else {//保存操作
                String sql = "select count(*) num from c_ques_ques where name= ? and questionnaire_id=? and deleted=0";
                List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name, quesId});
                Map returnMmap = list.get(0);
                if (Integer.valueOf(String.valueOf(returnMmap.get("num"))) == 0) {
                    map.put("code", "0");
                    map.put("msg", "success");
                } else {
                    map.put("code", "1");
                    map.put("msg", "此问题名称已经存在，请更改后重试。");
                }

            }
        } catch (Exception e) {
            logger.error(e);
        }
        return map;
    }

    @RequestMapping(params = "dataRefresh")
    @ResponseBody
    public List<Map<String, Object>> dataRefresh(HttpServletRequest request) {
        String qqid = request.getParameter("qqid");//问题主键组合
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            String sql = "select question_no,ques_ques_id,name from c_ques_ques where ques_ques_id in (" + qqid + ") ";
            list = commonService.findForJdbc(sql);
        } catch (Exception e) {
            logger.error(e);
        }
        return list;
    }

    /**
     * 新增及修改的数据处理
     *
     * @param entity
     * @return
     */
    @RequestMapping(params = "saveorupdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveorupdate(CQuesQuesEntity entity) {
        AjaxJson j = new AjaxJson();
        Integer quesType = Integer.valueOf(entity.getQuesType());//1:纯单选 2:纯多选 3:纯回答 4:单选+回答 5:多选+回答 ques_type
        if (quesType == 1 || quesType == 4) {
            entity.setSelectNum(1);
        } else if (quesType == 2 || quesType == 5) {
            entity.setSelectNum(2);
        } else {
            entity.setSelectNum(0);
        }
        try {
            if (entity.getId() != null) {//修改操作
                CQuesQuesEntity obj = commonService.getEntity(CQuesQuesEntity.class, entity.getId());
                MyBeanUtils.copyBeanNotNull2Bean(entity, obj);
                commonService.saveOrUpdate(obj);
                j.setMsg("操作成功");
            } else {//保存操作
                entity.setDeleted(0);
                commonService.save(entity);
                j.setMsg("操作成功");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }


    /**
     * 删除操作
     *
     * @param entity
     * @return
     */
    @RequestMapping(params = "del", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson del(CQuesQuesEntity entity, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            if (entity.getId() != null) {//修改
                entity = commonService.get(CQuesQuesEntity.class, entity.getId());
                entity.setDeleted(1);
//                commonService.delete(entity);
                commonService.saveOrUpdate(entity);
                j.setMsg("操作成功");
            } else {
                j.setMsg("问题不存在，请刷新后重试。");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }


    /**
     * 禁用或者启动操作
     *
     * @param entity
     * @return
     */
    @RequestMapping(params = "stop_or_start", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson stop_or_start(CQuesQuesEntity entity, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            if (entity.getId() != null) {//修改
                entity = commonService.get(CQuesQuesEntity.class, entity.getId());
                if (entity.getEffective() == 0)
                    entity.setEffective(1);
                else
                    entity.setEffective(0);
//                commonService.delete(entity);
                commonService.saveOrUpdate(entity);
                j.setMsg("操作成功");
            } else {
                j.setMsg("问题不存在，请刷新后重试。");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }
}
